package dinner.web.eat;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import dinner.web.Eat;
import dinner.web.libs.IOUtils;

public class EatDB {

	public static List<Eat> getEatArchiveForUser(String login, Calendar data) {
		List<Eat> eats = tryRead(login, data);
		if (eats == null) {
			eats = loadEatDefault(data);
		}
		return eats;
	}

	public static void setEatArchiveForUser(String login, List<Eat> eats, Calendar data) {
		File path = new File(IO.getDBForDate(data), login + ".db");
		IOUtils.write(eats, path);
	}

	protected static List<Eat> loadEatDefault(Calendar data) {
		List<Eat> list = new ArrayList<Eat>();
		List<MenuItem> menuItems = MenuDB.getListForDay(data);
		for (MenuItem I : menuItems) {
			if (I.isEnabled()) {
				list.add(I);
			}
		}
		return list;
	}

	protected static List<Eat> tryRead(String login, Calendar data) {
		File path = new File(IO.getDBForDate(data), login + ".db");
		List<Eat> eats = IOUtils.read(path, Eat.class);
		return eats == null ? null : (eats.size() == 0 ? null : eats);
	}

	public static void clearData() {
		File path = new File(IO.getDBForCurrentDate());
		File[] datas = path.listFiles(new FileFilter() {

			@Override
			public boolean accept(File pathname) {
				return pathname.getName().endsWith(".db");
			}
		});
		for (File f : datas) {
			f.delete();
		}
	}

	public static void clearData(String logined) {
		File path = new File(IO.getDBForCurrentDate(), logined + ".db");
		path.delete();
	}
}
